import datetime
import logging
from dataclasses import dataclass

from src.application.order.uow import OrderUoW
from src.application.user.exceptions import NotEnoughBalance
from src.domain.order.value_objects import OrderId
from src.infrastructure.date_helpers import get_date_time

logger = logging.getLogger(__name__)


@dataclass(frozen=True)
class SetOrderAutorenew:
    order_id: int
    autorenew: bool


class SetOrderAutorenewHandler:
    def __init__(
        self,
        *,
        uow: OrderUoW,
    ) -> None:
        self._uow = uow

    async def __call__(self, command: SetOrderAutorenew) -> None:
        order_id = OrderId(command.order_id)
        order = await self._uow.order_repo.acquire_order_by_id(order_id)

        order.set_autorenew(command.autorenew)

        try:
            await self._uow.order_repo.update_order(order)
        except Exception as err:
            await self._uow.rollback()
            raise err

        await self._uow.commit()

        logger.info(f"Order №{command.order_id} autorenew set to {command.autorenew}")
